package com.zyh;




import com.zyh.util.JwtUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
@Component
public class CheckLoginFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //提前判断是否是user模块
        ServerHttpRequest request = exchange.getRequest();
        String uri = request.getURI().toString();//请求路径
        if(uri.indexOf("/user-module/")>-1){
            return chain.filter(exchange);//放行请求
        }
        //1.获取请求头里面的token，
        List<String> authorization = request.getHeaders().get("authorization");
        if(authorization!=null&&authorization.size()>0){
            String token = authorization.get(0);
            //2.判断token是否正确
            try{
                JwtUtils.verify(token);
                return chain.filter(exchange);//放行请求
            }catch (Exception e){
                //拦截
                exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
                return exchange.getResponse().setComplete();
            }
        }
        //拦截
        exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
        return exchange.getResponse().setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
